using UnityEngine;

namespace Gj
{
    public class TouchPart : BasePart
    {
        private Notice _notice;
        private RealObject _self;

        public void Set(Notice notice)
        {
            _notice = notice;
        }

        public void Init(RealObject target)
        {
            _self = target;
        }

        public void Stop()
        {
            var entity = _self.GetEntity();
            var manager = ObjectService.EntityManager;
            manager.RemoveComponent<RayHitsData>(entity);
            manager.RemoveComponent<CastRayData>(entity);
        }

        public void Check()
        {
            var entity = _self.GetEntity();
            var manager = ObjectService.EntityManager;
            if (manager.HasComponent<RayHitsData>(entity))
            {
                var rayHitsDatas = manager.GetBuffer<RayHitsData>(entity);
                if (rayHitsDatas.Length > 0)
                    for (var i = 0; i < rayHitsDatas.Length; i++)
                    {
                        var rayHitsData = rayHitsDatas[i];
                        if (rayHitsData.entity == entity) break;
                        if (manager.HasComponent<EntityData>(rayHitsData.entity))
                        {
                            var element = ControlService.single.Get(rayHitsData.entity);
                            if (_notice.Filter(element))
                            {
                                _notice.Touch(element);
                                break;
                            }
                        }
                    }

                manager.RemoveComponent<RayHitsData>(entity);
            }

            var start = _self.GetPosition();
            var end = start + new Vector3(0, 1, 0);
            manager.AddComponentData(entity,
                new CastRayData { Start = start, End = end, isScan = true, multiple = true });
        }

        public interface Notice
        {
            void Touch(RealObject element);
            bool Filter(RealObject element);
        }
    }
}